package cn.znzz.cjm.mydetail;

import cn.znzz.cjm.domain.LoginUser;
import cn.znzz.cjm.domain.Permission;
import cn.znzz.cjm.mapper.LoginUserMapper;
import cn.znzz.cjm.mapper.PermissionMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

@Service
public class MyUserDetailsService implements UserDetailsService{

    @Autowired
    private LoginUserMapper loginUserMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(username);
        loginUser=loginUserMapper.selectOne(loginUser);
        System.out.println(loginUser);
        //拿到登录用户所拥有的权限
        ArrayList<SimpleGrantedAuthority> authr = new ArrayList<>();
        if(loginUser!=null){
            List<Permission> permissions=permissionMapper.selectPermisson(loginUser.getId());
            for (Permission permission:permissions){
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(permission.getSn());
                authr.add(simpleGrantedAuthority);
            }
        }
        User user = new User(loginUser.getUsername(),loginUser.getPassword(),authr);
        return user;
    }
}
